define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'question/question/index' + location.search,
                    add_url: 'question/question/add',
                    edit_url: 'question/question/edit',
                    del_url: 'question/question/del',
                    multi_url: '',
                    import_url: '',
                    table: 'question',
                }
            });

            var table = $("#table");
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), operate: 'LIKE'},
                        {field: 'classid', title: __('ClassID'), operate: 'LIKE', searchable:false},
                        {field: 'cover', title: __('Cover'), events: Table.api.events.image, formatter: Table.api.formatter.image, operate: false},
                        
                        {field: 'sort', title: __('Sort'), operate: 'LIKE',  searchable:false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, searchable:false},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime, searchable:false},
                        {field: 'status', title: __('Status'), formatter: Table.api.formatter.status, searchList: {"0": __('Normal'), "1": __('Disable'), "2": __('Complaint')}, custom: {"0":'success', "1":'danger', "2":'disabled'}},
                        {
                            field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate, buttons: [
                                {
                                    name: 'edit_result',
                                    title: __('Edit result'),
                                    text: __('Edit result'),
                                    extend: `data-area='["1100px","600px"]'`,
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-pencil',
                                    url: 'question/question/component',
                                    hidden: function (row) {
                                        return false;
                                    }
                                }
                            ]
                        }

                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        component: function () {
            Table.api.init();
            this.table.question();
            let question_ids = $("#question_ids").val();
            this.table.data = JSON.parse(question_ids);
            let that = this;

            $(function(){

                let qids = $("#qids").val();

                $.ajax({
                    url: 'question/question/ajaxQuestionInfo',
                    type: 'post',
                    data: {id:qids},
                    dataType: 'json',
                    success: function (ret) {
                     
                        //显示问题
                        if(ret.question.length > 0){

                            let question_html = "";

                            ret.question.forEach((item, index) => {

                                question_html += `
                                <div class="json_list">
                                      <div class="json_left">
                                          <div class="question">
                                              <input type="text" class="form-control" value="${item.id}、${item.title}" readonly/>
                                              <input type="hidden" name="row[question][${index}][id]" value="${item.id}"/>
                                              </div>
                                              `;
                                let questiondata = JSON.parse(item.settingdata);
                                //console.log(questiondata);
                                questiondata.forEach((it, id) => {
                                    //console.log(it);
                                    question_html += `<div class="answer">
                                                <input type="text" class="form-control" style="width: 70%;" value="${it.option}：${it.intro}" readonly/>
                                                <span style="height: 31px;padding: 0px 0 0 6px;font-size: 12px;line-height: 31px;">分值:${it.score}</span>
                                            
                                            </div>`;
                                })
                
                                question_html += `
                                            </div>
                                            <div>                               
                                                <span class="btn btn-sm btn-danger btn-remove" data-question="${item.id}">
                                                    <i class="fa fa-times"></i>
                                                </span>
                                                <span class="btn btn-sm btn-primary btn-dragsort">
                                                    <i class="fa fa-arrows"></i>
                                                </span>
                                            </div>
                                        </div>
                                    `;

                            })

                            $("#question").append(question_html);

                        }

                        //显示结果
                        if(ret.result.length > 0){

                            let result_html = "";
                            ret.result.forEach((item, index) => {

                                result_html += `
                                    <dl class="fieldlist" data-template="content_tpl">
                                        <dd class="form-inline question json_list">
                                        
                                            <div class="json_left" style="width:100%;">
                                                <span style="color: #F44336;margin-right: 10px;">${item.tags_name}:</span>
                                                <input type="text" value="${item.left}" class="form-control" placeholder="左区间分数" size="6" readonly>
                                                <input type="text" value="${item.right}" class="form-control" placeholder="右区间分数" size="6" readonly>
                                                <textarea class="form-control" cols="50" rows="4" style="margin-top:10px;vertical-align: top;" placeholder="结果说明" readonly>${item.content}</textarea>
                                            </div>
                                        </dd>
                                    </dl>
                                `;

                            })

                            $("#old_Result_list").append(result_html);
                        }

                    }
                });

            });


            //显示标签原始数据
            $(document).on("click", "#old_Result", function () {

                var display = $('#old_Result_list').css('display');
                if(display == 'none'){
                    $("#old_Result_list").css("display","block");
                }else{
                    $("#old_Result_list").css("display","none");
                }

            })

            //console.log(Fast)
            //移除控制
            $("#question").on("click", ".btn-remove", function () {
                let question_id = $(this).data('question');
                $(this).closest(".json_list").remove();
                let index = that.table.data.indexOf(question_id);
                that.table.data.splice(index, 1);
            });


            let cop = [];
            //下拉选择驱动
            $("#c-component_id").data("params", function (obj) {
                let component_texts = $("#c-component_id").selectPageText();
                let component_ids = $("#c-component_id").val();
               
                if (!component_ids) {
                    $("#question_Result").html("");//清除全部
                    cop.component_ids = [];
                    cop.list = [];
                    cop.question = [];
                    return;
                }
                //每次都是全部
                let component_ids_arr = component_ids.split(',');              
                let component_text_arr = component_texts.split(',');
                //赋值
                if (cop.list.length < component_ids_arr.length) {
                    //不存在就追加，按顺序的                
                    component_ids_arr.forEach((item, index) => {
                        if (cop.component_ids.indexOf(item) == -1) {
                            cop.component_ids.push(item);
                            cop.list.push({
                                id: item,
                                title: component_text_arr[index],
                                type: 1,
                                question:[],
                                result:[]
                            });

                            addResult(item, component_text_arr[index], index);
                        }
                    })
                }
                //删除
                if (cop.list.length > component_ids_arr.length) {
                    
                    cop.list.forEach((item, index) => {
                        if (component_ids_arr.indexOf(item.id) == -1) {
                            cop.component_ids.splice(index, 1);
                            cop.list.splice(index, 1);
                            $("#content_tpl_"+item.id).remove();
                        }
                    })
                }
            });


            //结果显示
            function addResult(id, title, index){
               
                let html = `
                            <dl class="fieldlist" data-template="content_tpl" id="content_tpl_${id}">
                                <dd class="form-inline question json_list">
                                  
                                    <div class="json_left" style="width:100%;">
                                        <span style="color: #F44336;margin-right: 10px;">${title}:</span>
                                        <input type="hidden" name="row[result][${index}][tags_id]" value="${id}" >
                                        <input type="text" name="row[result][${index}][left]" class="form-control" placeholder="左区间分数" size="6">
                                        <input type="text" name="row[result][${index}][right]" class="form-control" placeholder="右区间分数" size="6">
                                        <textarea name="row[result][${index}][content]" class="form-control" cols="50" rows="4" style="margin-top:10px;vertical-align: top;" placeholder="结果说明"></textarea>
                                    </div>
                                </dd>
                               
                            </dl>
                     `;


                $("#question_Result").append(html);

            }

            setTimeout(() => {
                //拖拽排序
                $("#question").dragsort({
                    itemSelector: 'div',
                    dragSelector: ".btn-dragsort",
                    dragEnd: function () {
                        console.log(77777)
                    },
                    placeHolderTemplate: "<div></div>"
                });
            }, 5000)

            Controller.api.bindevent();
        },
        table: {
            data: [],
            question: function () {
                // 表格1
                var table = $("#table");
                table.bootstrapTable({
                    url: 'questionlist/questionlist/select',
                    toolbar: '#toolbar',
                    sortName: 'id',
                    search: false,
                    columns: [
                        [
                            { field: 'state', checkbox: true, },
                            { field: 'id', title: __('Id') },
                            {field: 'classid', title: __('ClassID'), operate: 'LIKE', searchable:false},
                            {field: 'title', title: __('Title'), operate: 'LIKE'},
                        ]
                    ]
                });

                // 为表格1绑定事件
                Table.api.bindevent(table);

                let that = this;
                
                // 获取选中项
                $(document).on("click", ".btn-selected", function () {
                    let question = table.bootstrapTable('getSelections');
                    
                    let is_ = false;
                    let qu_val = $("#question_val").val();
                   
                    //判断是否存在问题列表
                    if(qu_val > 0){
                        let question_val = JSON.parse($("#question_val").val());
                        if(question_val != "" || question_val != null){
                            question_val.forEach((ite, index) => {
                                if (that.data.indexOf(parseInt(ite.id)) == -1) {
                                    that.data.push(parseInt(ite.id));
                                }
                            })
                        }
                    }

                    question.forEach((item, index) => {
            
                        if (that.data.indexOf(item.id) == -1) {
                            that.data.push(item.id);
                            that.refresh(item, that.data.length - 1);

                        } else {
                            is_ = true;
                        }

                    })
                    if (is_) {
                        Toastr.error(Fast.lang('已过滤重复题目!'));
                    }
                });

            },
            refresh: function (item, index) {
            
                let html = `
                      <div class="json_list">
                            <div class="json_left">
                                <div class="question">
                                    <input type="text" class="form-control" value="${item.id}、${item.title}" readonly/>
                                    <input type="hidden" name="row[question][${index}][id]" value="${item.id}"/>
                                    </div>
                                    `;
                let questiondata = JSON.parse(item.settingdata);
                //console.log(questiondata);
                questiondata.forEach((it, id) => {
                    //console.log(it);
                    html += `<div class="answer">
                                <input type="text" class="form-control" style="width: 70%;" value="${it.option}：${it.intro}" readonly/>
                                <span style="height: 31px;padding: 0px 0 0 6px;font-size: 12px;line-height: 31px;">分值:${it.score}</span>
                             
                            </div>`;
                })

                html += `
                            </div>
                            <div>                               
                                <span class="btn btn-sm btn-danger btn-remove" data-question="${item.id}">
                                    <i class="fa fa-times"></i>
                                </span>
                                <span class="btn btn-sm btn-primary btn-dragsort">
                                    <i class="fa fa-arrows"></i>
                                </span>
                            </div>
                        </div>
                    `;
                $("#question").append(html);
            }
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: { //渲染的方法
             
            }
        }
    };
    return Controller;
});